let express = require("express");
// let ejs = require("ejs");
// let mysql = require("mysql");
let router = express.Router();

//加载数据库配置
let db = require("../model/db");

//解析表单的获取值
router.use(express.urlencoded({ extended: false }));


router.get("/index", async (req, res) => {
    //err 成功或者失败  
    //data 查询出来的数据
    let sql = `select * from stu_student`;
    let [err, data] = await db.query(sql);
    // console.log(data);
    if (err) {
        res.send({ "code": "400", "mag": "查询失败" })
    } else {
        res.send({ "code": "200", "mag": "查询成功", data: data ,"mag1":"/edit.html"})
    }
})

//渲染添加页面
router.get("/add", (req, res) => {
    res.render("add.html")
})

// router.post("/add",(req,res)=>{

// })

// 处理表单提交
router.post("/add", async (req, res) => {
    //获取表单中提交数据
    //console.log(req.body);
    // res.redirect("/index.html")
    // return
    let { username, sex, age } = req.body;
    console.log(username, sex, age);
    if (username && sex && age) {
        try {
            let sql = `insert into stu_student (name,sex,age) value ("${username}","${sex}",${age})`;
            let [err, data] = await db.query(sql);
            console.log("success")
            res.send({ "code": "200", "mag": "index.html" })
        } catch (err) {
            res.send({ "code": "400", "mag": "添加失败" })
            
        }
    } else {
        console.log(222)
        res.send({ "code": "400", "mag": "添加失败" })
    }
    //上面获取表单的数据添加数据库中
})


//删除功能
router.get("/del", async(req, res) => {
    //res.send("进入")
    //console.log(req.query.id);
    let id = req.query.id;
    console.log(id);
    let sql = `delete from stu_student where id=${id}`;
    let [err, data] = await db.query(sql);

        if (err) {
            res.send({ "code": "400", "mag": "删除失败" })
        } else {
            res.send({ "code": "200", "mag": "/index.html"})
        }
    // })
})

//渲染修改页面
router.get("/edit", async(req, res) => {
    //根据id查询对应数据 
    let id = req.query.id;
    let sql = `select * from stu_student where id=${id}`;
    let [err, data] = await db.query(sql);

    //res.render("edit.html")
    //执行sql语句
    // connection.query(sql, (err, result) => {
        if (err) {
            res.send({ "code": "400", "mag": "查找失败"})
        } else {
            //console.log(result);
            res.send({ "code": "200", "mag": "查找成功", data:data} )
        }
})

//处理修改后的数据
router.post("/update", async(req, res) => {
    //获取文本框输入的值
    let { id, name, sex, age } = req.body;
    //console.log(id, 11111);
    try {
        let sql = `update stu_student set name="${name}",sex="${sex}",age=${age} where id=${id}`;
        let [err, data] = await db.query(sql);
        //执行sql语句
            if (err) {
                res.send({"code":400,"mag": "修改失败"})
            } else {
                res.send({"code":200,"mag": "/index.html",})
            }
    } catch (error) {
        res.send({"code":400,"mag": "修改失败"})
    }
})

module.exports = router;